<template>
  <div class="field-config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div>
            <h3>区块字段配置</h3>
            <p class="text-muted">{{ blockInfo.name }} ({{ blockInfo.alias }})</p>
          </div>
          <div class="header-actions">
            <el-button @click="router.back()">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <el-button type="primary" @click="handleAddField">
              <el-icon><Plus /></el-icon>
              添加字段
            </el-button>
            <el-button type="info" @click="handleInitDefaultFields" v-if="blockInfo.type">
              初始化默认字段
            </el-button>
            <el-button type="success" @click="handleSaveFields" :loading="saving">
              <el-icon><Check /></el-icon>
              保存配置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 字段列表 -->
      <div v-if="fields.length > 0" class="fields-container">
        <draggable
          v-model="fields"
          item-key="id"
          handle=".drag-handle"
          @end="updateFieldOrder"
        >
          <template #item="{ element: field, index }">
            <div class="field-item" :class="{ editing: field.editing }">
              <div class="field-header">
                <div class="field-info">
                  <el-icon class="drag-handle"><Rank /></el-icon>
                  <span class="field-name">{{ field.label || field.name || '新字段' }}</span>
                  <el-tag :type="getFieldTypeColor(field.type)" size="small">
                    {{ getFieldTypeLabel(field.type) }}
                  </el-tag>
                  <el-tag v-if="field.required" type="danger" size="small">必填</el-tag>
                </div>
                <div class="field-actions">
                  <el-button size="small" @click="editField(field, index)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteField(index)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 字段编辑表单 -->
              <div v-if="field.editing" class="field-form">
                <el-form :model="field" label-width="100px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="字段名称" required>
                        <el-input v-model="field.name" placeholder="英文字段名" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="字段标签" required>
                        <el-input v-model="field.label" placeholder="中文显示名" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="字段类型" required>
                        <el-select v-model="field.type" @change="onFieldTypeChange(field)">
                          <el-option
                            v-for="type in fieldTypes"
                            :key="type.value"
                            :label="type.label"
                            :value="type.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否必填">
                        <el-switch v-model="field.required" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="字段描述">
                    <el-input v-model="field.description" placeholder="字段说明" />
                  </el-form-item>

                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="默认值">
                        <el-input v-model="field.defaultValue" placeholder="默认值" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="占位符">
                        <el-input v-model="field.placeholder" placeholder="输入提示" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <!-- 选项配置 -->
                  <div v-if="needOptions(field.type)" class="options-config">
                    <el-form-item label="选项配置">
                      <div class="options-list">
                        <div
                          v-for="(option, optionIndex) in field.options"
                          :key="optionIndex"
                          class="option-item"
                        >
                          <el-input
                            v-model="option.value"
                            placeholder="选项值"
                            style="width: 200px; margin-right: 10px"
                          />
                          <el-input
                            v-model="option.label"
                            placeholder="选项标签"
                            style="width: 200px; margin-right: 10px"
                          />
                          <el-button
                            size="small"
                            type="danger"
                            @click="removeOption(field, optionIndex)"
                          >
                            删除
                          </el-button>
                        </div>
                        <el-button size="small" @click="addOption(field)">
                          添加选项
                        </el-button>
                      </div>
                    </el-form-item>
                  </div>

                  <div class="form-actions">
                    <el-button type="primary" @click="saveField(field, index)">
                      保存
                    </el-button>
                    <el-button @click="cancelEdit(field)">
                      取消
                    </el-button>
                  </div>
                </el-form>
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无字段配置">
          <el-button type="primary" @click="handleAddField">
            添加第一个字段
          </el-button>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus, Check, Edit, Delete, Rank } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { blockApi } from '@/api/block'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const blockInfo = ref({
  id: route.query.blockId as string, // 保持字符串格式，避免精度丢失
  name: '',
  alias: ''
})
const fields = ref<any[]>([])
const fieldTypes = ref([
  { value: 'text', label: '单行文本' },
  { value: 'textarea', label: '多行文本' },
  { value: 'number', label: '数字' },
  { value: 'email', label: '邮箱' },
  { value: 'url', label: '链接' },
  { value: 'password', label: '密码' },
  { value: 'date', label: '日期' },
  { value: 'datetime', label: '日期时间' },
  { value: 'select', label: '下拉选择' },
  { value: 'radio', label: '单选按钮' },
  { value: 'checkbox', label: '复选框' },
  { value: 'image', label: '图片' },
  { value: 'file', label: '文件' },
  { value: 'editor', label: '富文本编辑器' }
])

// 方法
const loadBlockInfo = async () => {
  try {
    const response = await blockApi.getInfo(blockInfo.value.id)
    if (response.code === 0) {
      blockInfo.value = { ...blockInfo.value, ...response.data }
    }
  } catch (error) {
    console.error('加载区块信息失败:', error)
  }
}

const loadFields = async () => {
  loading.value = true
  try {
    console.log('加载区块字段配置:', blockInfo.value.id)
    const response = await blockApi.getFields(blockInfo.value.id)
    console.log('字段加载响应:', response)

    if (response.code === 0) {
      fields.value = (response.data || []).map((field: any) => ({
        ...field,
        editing: false,
        options: field.options ? JSON.parse(field.options) : [],
        // 转换整数为布尔值，符合前端期望
        required: field.required === 1,
        status: field.status === 1
      }))
      console.log('加载的字段列表:', fields.value)

      // 如果没有字段配置，根据区块类型初始化默认字段
      if (fields.value.length === 0 && blockInfo.value.type) {
        await initDefaultFields()
      }
    }
  } catch (error) {
    console.error('加载字段配置失败:', error)
    ElMessage.error('加载字段配置失败')
  } finally {
    loading.value = false
  }
}

// 根据区块类型初始化默认字段
const initDefaultFields = async (forceInit = false) => {
  try {
    console.log('初始化默认字段，区块类型:', blockInfo.value.type)
    const response = await blockApi.getDefaultFields(blockInfo.value.type)
    console.log('默认字段响应:', response)

    if (response.code === 0 && response.data && response.data.length > 0) {
      fields.value = response.data.map((field: any, index: number) => ({
        ...field,
        id: `default_${Date.now()}_${index}`,
        editing: false,
        options: field.options ? JSON.parse(field.options) : [],
        // 转换整数为布尔值，符合前端期望
        required: field.required === 1,
        status: field.status === 1
      }))

      // 自动保存默认字段
      await saveFieldsToBackend()

      if (forceInit) {
        ElMessage.success(`已重新初始化${getBlockTypeLabel(blockInfo.value.type)}类型区块的默认字段`)
      } else {
        ElMessage.success(`已为${getBlockTypeLabel(blockInfo.value.type)}类型区块初始化默认字段`)
      }
    } else {
      if (forceInit) {
        ElMessage.warning(`${getBlockTypeLabel(blockInfo.value.type)}类型暂无默认字段模板`)
      }
    }
  } catch (error) {
    console.error('初始化默认字段失败:', error)
    if (forceInit) {
      ElMessage.error('初始化默认字段失败')
    }
  }
}

// 获取区块类型标签
const getBlockTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    'carousel': '轮播图',
    'article_list': '文章列表',
    'news': '新闻',
    'activity': '活动',
    'discussion': '讨论',
    'image': '图片',
    'text': '文本',
    'html': 'HTML',
    'video': '视频',
    'list': '列表',
    'custom': '自定义'
  }
  return typeMap[type] || type
}

// 手动初始化默认字段
const handleInitDefaultFields = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要初始化${getBlockTypeLabel(blockInfo.value.type)}类型的默认字段吗？\n\n这将会覆盖当前的字段配置！`,
      '初始化默认字段',
      {
        type: 'warning',
        confirmButtonText: '确定初始化',
        cancelButtonText: '取消'
      }
    )

    await initDefaultFields(true)
  } catch (error) {
    // 用户取消
  }
}

const handleAddField = () => {
  // 先关闭其他编辑中的字段
  fields.value.forEach(f => f.editing = false)

  const newField = {
    id: `new_${Date.now()}_${fields.value.length}`,
    name: `field_${fields.value.length + 1}`, // 给一个默认名称
    label: `字段${fields.value.length + 1}`, // 给一个默认标签
    type: 'text',
    description: '',
    defaultValue: '',
    placeholder: '',
    required: false,
    options: [],
    orderNum: fields.value.length + 1,
    status: 1,
    editing: true // 新字段直接进入编辑状态
  }

  fields.value.push(newField)

  // 滚动到新字段位置
  nextTick(() => {
    const fieldElements = document.querySelectorAll('.field-item')
    const lastField = fieldElements[fieldElements.length - 1]
    if (lastField) {
      lastField.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

const editField = (field: any, index: number) => {
  // 关闭其他编辑中的字段
  fields.value.forEach(f => f.editing = false)
  field.editing = true
}

const saveField = async (field: any, index: number) => {
  if (!field.name || !field.label) {
    ElMessage.error('字段名称和标签不能为空')
    return
  }

  try {
    field.editing = false

    // 立即保存到后端
    await saveFieldsToBackend()

    ElMessage.success('字段保存成功')
  } catch (error) {
    console.error('保存字段失败:', error)
    ElMessage.error('保存字段失败')
    // 如果保存失败，重新进入编辑状态
    field.editing = true
  }
}

const cancelEdit = (field: any) => {
  field.editing = false
}

const deleteField = async (index: number) => {
  const field = fields.value[index]
  try {
    await ElMessageBox.confirm(
      `确定要删除字段"${field.label || field.name}"吗？\n\n⚠️ 删除后将立即保存到数据库，无法撤销！`,
      '删除字段确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )

    console.log('删除字段:', field)

    // 从数组中删除字段
    fields.value.splice(index, 1)

    // 立即保存到后端
    await saveFieldsToBackend()

    ElMessage.success(`字段"${field.label || field.name}"删除成功`)
  } catch (error) {
    // 用户取消删除或保存失败
    if (error !== 'cancel') {
      console.error('删除字段失败:', error)
      ElMessage.error('删除字段失败: ' + (error.message || '未知错误'))
    }
  }
}

const onFieldTypeChange = (field: any) => {
  if (needOptions(field.type) && (!field.options || field.options.length === 0)) {
    field.options = [{ value: '', label: '' }]
  }
}

const needOptions = (type: string) => {
  return ['select', 'radio', 'checkbox'].includes(type)
}

const addOption = (field: any) => {
  if (!field.options) field.options = []
  field.options.push({ value: '', label: '' })
}

const removeOption = (field: any, index: number) => {
  field.options.splice(index, 1)
}

const updateFieldOrder = () => {
  fields.value.forEach((field, index) => {
    field.orderNum = index + 1
  })
}

// 保存字段到后端的核心方法
const saveFieldsToBackend = async () => {
  const fieldsData = fields.value.map(field => {
    const fieldData = {
      ...field,
      options: field.options && field.options.length > 0 ? JSON.stringify(field.options) : null,
      editing: undefined, // 移除编辑状态
      // 转换布尔值为整数，符合后端期望
      required: field.required ? 1 : 0,
      status: field.status ? 1 : 0
    }

    // 如果是临时ID（包含字符串前缀），则不发送ID，让后端自动生成
    if (typeof fieldData.id === 'string' && (fieldData.id.startsWith('new_') || fieldData.id.startsWith('default_'))) {
      delete fieldData.id
    }

    return fieldData
  })

  console.log('保存字段数据到后端:', {
    blockId: blockInfo.value.id,
    fieldsCount: fieldsData.length,
    fields: fieldsData
  })

  const response = await blockApi.saveFields(blockInfo.value.id, fieldsData)
  console.log('字段保存响应:', response)

  if (response.code === 0) {
    await loadFields() // 重新加载
    return true
  } else {
    throw new Error(response.msg || '保存失败')
  }
}

// 手动保存字段配置
const handleSaveFields = async () => {
  saving.value = true
  try {
    await saveFieldsToBackend()
    ElMessage.success('字段配置保存成功')
  } catch (error) {
    console.error('保存字段配置失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const getFieldTypeLabel = (type: string) => {
  const typeItem = fieldTypes.value.find(t => t.value === type)
  return typeItem ? typeItem.label : type
}

const getFieldTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    text: '',
    textarea: 'info',
    number: 'warning',
    select: 'success',
    radio: 'success',
    checkbox: 'success',
    image: 'danger',
    file: 'danger',
    editor: 'info'
  }
  return colorMap[type] || ''
}

onMounted(() => {
  if (!blockInfo.value.id) {
    ElMessage.error('缺少区块ID参数')
    router.back()
    return
  }
  
  loadBlockInfo()
  loadFields()
})
</script>

<style scoped>
.field-config-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.text-muted {
  color: #999;
  margin: 0;
}

.fields-container {
  margin-top: 20px;
}

.field-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 16px;
  background: #fff;
  transition: all 0.3s;
}

.field-item.editing {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.15);
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.field-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.drag-handle {
  cursor: move;
  color: #c0c4cc;
}

.field-name {
  font-weight: 500;
  color: #303133;
}

.field-actions {
  display: flex;
  gap: 8px;
}

.field-form {
  padding: 20px;
  background: #fafafa;
}

.options-config {
  margin-top: 16px;
}

.options-list {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background: #fff;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.form-actions {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}
</style>
